package com.atxwq.shop.manager.serivce.impl;

import com.alibaba.excel.EasyExcel;
import com.atxwq.shop.common.exception.GlobalException;
import com.atxwq.shop.manager.listener.ExcelListener;
import com.atxwq.shop.manager.mapper.CategoryMapper;
import com.atxwq.shop.manager.serivce.CategoryService;
import com.atxwq.shop.model.entity.product.Category;
import com.atxwq.shop.model.vo.common.ResultCodeEnum;
import com.atxwq.shop.model.vo.product.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Date 2025/5/13 09:58
 * @Created by 12336
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 分类列表，每次只查一层数据，提高效率
     * @param id
     * @return
     */
    @Override
    public List<Category> findCategoryList(Long id) {
        //1.根据id条件查询返回list集合
        List<Category> list = categoryMapper.selectCategoryList(id);
        //todo 循环查询数据库效率差，待后续优化
        if(!CollectionUtils.isEmpty(list)) {

            // 遍历分类的集合，获取每一个分类数据
            list.forEach(item -> {

                // 查询该分类下子分类的数量
                int count = categoryMapper.countByParentId(item.getId());
                if(count > 0) {
                    item.setHasChildren(true);
                } else {
                    item.setHasChildren(false);
                }

            });
        }
        return list;

    }

    /**
     * 导出数据
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //1.设置响应头信息(ms-excel是指微软excel)
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            String fileName = URLEncoder.encode("分类数据", "UTF-8");
            //设置响应头信息为下载信息
            response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");

            //2.调用mapper的方法，查询所有分类数据
            List<Category> categories =  categoryMapper.findAll();

            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>();
            //类型转换
            for(Category category : categories){
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo, CategoryExcelVo.class);
                categoryExcelVoList.add(categoryExcelVo);
            }
            //3.调用easyExcel的写方法完成操作
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class)
                     .sheet("分类数据")
                     .doWrite(categoryExcelVoList);

        } catch (Exception e) {
            throw new GlobalException(ResultCodeEnum.DATA_ERROR);
        }
    }

    /**
     * 导入数据
     * @param file
     */
    @Override
    public void importData(MultipartFile file) {
        //监听器
        ExcelListener<CategoryExcelVo> excelListener = new ExcelListener(categoryMapper);
        try {
            EasyExcel.read(file.getInputStream(), CategoryExcelVo.class,excelListener).sheet().doRead();
        } catch (IOException e) {
            throw new GlobalException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
